package com.demo.client;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

import com.demo.data.Data;
import com.demo.data.Film;

public class Client 
{
	public static Socket clientSocket;
	public static DataOutputStream dos;
	public Client() 
	{
		try
		{
			clientSocket = new Socket("localhost", 11230);
			dos = new DataOutputStream(clientSocket.getOutputStream());
			dos.writeUTF("Nguyen Van Tuan");
			clientSocket.close();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public void connect(String host, int port) 
	{
		try
		{
			clientSocket = new Socket(host, port);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
	}
	public void sendRequest(int requestCode, Object data) 
	{
		try
		{
			ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
			out.writeInt(requestCode);
			out.writeObject(data);
			out.close();
		    
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("finally")
	public Object receivedData() 
	{
		try
		{
			ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
			int resultCode = in.readInt();
			if(resultCode == Data.MSG_GET_DATA)
			{
				return (ArrayList<Film>) in.readObject();
			}
			return resultCode;
		    
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
		}
		finally
		{
			return -1;
		}
	}
	
}
